package algorithm;

import io.OutputWriter;
import java.io.IOException;
import pac.SearchDatastructure;

public class ApproxCompleteSearch {
	private SearchDatastructure searcher;
	private OutputWriter outputter;
	
	public ApproxCompleteSearch ( SearchDatastructure I, OutputWriter O ) throws IOException 
	{
		searcher = I;
		outputter = O;
	} 
	
	public void doApproximatePairwiseSearch() throws IOException {
		searcher.startTimeMs = System.currentTimeMillis( );				
		
		int lengthOfBitSet = 2*searcher.snpList.length; 
		int progress = 1;
		
		for(int snp1=1; snp1<lengthOfBitSet; snp1++) {
			
			for(int snp2=0; snp2<snp1; snp2++) {
			
				int chr1 = searcher.snpList[(int) Math.floor(snp1/2)].getChromosome();
				int chr2 = searcher.snpList[(int) Math.floor(snp2/2)].getChromosome();
				double cm1 = searcher.snpList[(int) Math.floor(snp1/2)].getCm_distance();
				double cm2 = searcher.snpList[(int) Math.floor(snp2/2)].getCm_distance();
				if( (chr1 == chr2) && Math.abs(cm1 - cm2) < searcher.userParams.getBlockSizeCm() )
					continue;
				
				int[] variableArray = new int[] {snp1, snp2};
				
				int[][][] noOfCaseCarriers = searcher.snpIndices.getObservedCaseCarriers(searcher.userParams, variableArray);
				double pvalueCaseOnly = searcher.significance.TestCasesOnly ( 2, noOfCaseCarriers );
				if ( pvalueCaseOnly > searcher.significance.getCaseOnlyThreshold (2) )				
					continue;
			
				int[][][] noOfControlCarriers = searcher.snpIndices.getObservedControlCarriers(searcher.userParams, variableArray);				
				double pvalueCaseControl = searcher.significance.TestCasesVsControls (2, noOfCaseCarriers, noOfControlCarriers );
				if ( pvalueCaseControl <= searcher.significance.getCaseControlThreshold ( 2 ) )
					outputter.WriteOutput(variableArray, noOfCaseCarriers, pvalueCaseOnly, noOfControlCarriers, pvalueCaseControl );
		
			}	//end snp2 loops
			
			if( snp1 > progress * (double) lengthOfBitSet/100 ) {
				System.out.println("Finished " + Math.pow(progress, 2)/100 + "% in " + (System.currentTimeMillis( ) - searcher.startTimeMs)/1000 + " seconds.");
				progress++;
		
			}	//end snp1 loop	

	}
	
		outputter.Close();
		System.out.println("=========");
		System.out.println("Done.");
		System.out.println("Interactions found are listed in " + searcher.userParams.getStage2Output());
		System.out.println("=========");
		return;
	}
	
}
